package org.java.io;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * ftp相关测试
 * Created by Administrator on 2016/10/18.
 */
public class FtpTest {

    public static void main(String[] args) {
        testUpload(); // 测试上传
        //testDownload(); // 测试下载
    }


    /**
     * FTP上传单个文件测试
     */
    public static void testUpload() {
        FTPClient ftpClient = new FTPClient();
        FileInputStream fis = null;

        try {
            ftpClient.connect("172.23.221.7");
            ftpClient.login("wevil", "wevil");

            File srcFile = new File("D:/tmp/中文.txt");
            fis = new FileInputStream(srcFile);
            //设置上传目录
            ftpClient.makeDirectory("/home/wevil/vsftpd/bigdata");
            ftpClient.changeWorkingDirectory("/home/wevil/vsftpd/bigdata");
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("UTF-8");
            //设置文件类型（二进制）
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.storeFile(new String("中文.txt".getBytes("UTF-8"),"iso-8859-1"), fis);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP客户端出错！", e);
        } finally {
            IOUtils.closeQuietly(fis);
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭FTP连接发生异常！", e);
            }
        }
    }

    /**
     * FTP下载单个文件
     * @param ip ftp地址
     * @param username ftp用户名
     * @param password ftp用户密码
     * @param remoteFileName ftp上要下载的文件地址
     * @param outPath 下载到本地的地址,要加文件名
      */
    public static void testDownload(String ip, String username, String password, String remoteFileName, String outPath) {
        FTPClient ftpClient = new FTPClient();
        FileOutputStream fos = null;

        try {
            ftpClient.connect(ip);
            ftpClient.login(username, password);

            fos = new FileOutputStream(outPath);

            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("UTF-8");
            //设置文件类型（二进制）
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			// 这里解决中文文件下载问题。
            ftpClient.retrieveFile(new String(remoteFileName.getBytes("UTF-8"),"iso-8859-1"), fos);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP客户端出错！", e);
        } finally {
            IOUtils.closeQuietly(fos);
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭FTP连接发生异常！", e);
            }
        }
    }
}
